package com.lagou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局过滤器，对所有路由生效
 */
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    //黑名单
    private static List<String> blackList = new ArrayList<>();

    static {
        //本地是0:0:0:0:0:0:0:1
        blackList.add("192.168.90.97");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        if (blackList.contains(clientIp)) {
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer wrap = response.bufferFactory().wrap("Request be denied!".getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //访问放行
        return chain.filter(exchange);
    }

    /**
     * 定义过滤器的顺序，数值越小越靠前
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
